<template>
  <div class="search_container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>图书管理员管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always">
      <!-- 搜索内容和导出区域 -->
      <el-row style="margin-bottom: 8px">
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog" size="large">添加管理员</el-button>
        </el-col>
        <el-col :span="2" style="float: right">
          <el-button type="primary" class="el-icon-printer" size="large" @click="exportToExcel">
            导出Excel
          </el-button>
        </el-col>
        <el-col :span="4" style="float: right"></el-col>
        <el-col :span="2" style="float: right"></el-col>
        <el-col :span="4" style="float: right"></el-col>
        <el-col :span="2" style="float: right">
          <el-button type="success" class="el-icon-full-screen" size="large" @click="fullScreen">
            全屏
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        border
        height="320"
        style="width: 100%"
        stripe
        id="pdfDom"
        :default-sort="{ prop: 'bookAdminId', order: 'ascending' }"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="Username" label="账号"></el-table-column>
        <el-table-column prop="BookAdminName" label="姓名"></el-table-column>
        <el-table-column prop="Email" label="邮箱"></el-table-column>
        <el-table-column prop="CreateTime" label="创建时间" sortable></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <!-- 修改按钮 -->
            <el-button type="primary" @click="showEditDialog(row.BookAdminID)">
              <el-icon><EditPen /></el-icon>
            </el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="removeUserById(row.BookAdminID)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页查询区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 3, 4, 5]"
        :page-size="queryInfo.pageSize"
        layout="total,  prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 修改公告的对话框 -->
      <el-dialog
        title="修改管理员"
        v-model="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="100px">
          <el-form-item label="姓名" prop="bookAdminName">
            <el-input v-model="editForm.bookAdminName"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="editForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="editForm.password" type="password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateBookAdmin">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加管理员的对话框 -->
      <el-dialog title="添加管理员" v-model="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="100px">
          <el-form-item label="姓名" prop="bookAdminName">
            <el-input v-model="addForm.bookAdminName"></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input v-model="addForm.userName"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addBookAdmin">添加管理员</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { getAdminList, addAdmin, getOneAdmin, postOneAdmin, delOneAdmin } from "../../api/api";
import * as XLSX from "xlsx";

let tableData = ref([]);
const editDialogVisible = ref(false);
const editForm = reactive({
  userName: "",
  password: "",
  email: "",
  bookAdminName: "",
  bookAdminId: 0,
});

const editFormRules = reactive({
  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      min: 5,
      max: 30,
      message: "长度在5到30个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 50,
      message: "长度在6到50个字符",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入正确的邮箱",
      trigger: "blur",
      type: "email",
    },
    {
      min: 6,
      max: 50,
      message: "长度在6到50个字符",
      trigger: "blur",
    },
  ],
  bookAdminName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
});
const addDialogVisible = ref(false);
const addForm = reactive({
  userName: "",
  password: "",
  email: "",
  bookAdminName: "",
});
const addFormRules = reactive({
  userName: [
    { required: true, message: "请输入账号", trigger: "blur" },
    {
      min: 5,
      max: 30,
      message: "长度在5到30个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 50,
      message: "长度在6到50个字符",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入正确的邮箱",
      trigger: "blur",
      type: "email",
    },
    {
      min: 6,
      max: 50,
      message: "长度在6到50个字符",
      trigger: "blur",
    },
  ],
  bookAdminName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
});
//增加表单校验
let addFormRef = ref();

const queryInfo = reactive({
  pageNum: 1,
  pageSize: 5,
  query: "",
  condition: "",
});
const total = ref(0);
const title = "图书管理员";
const json_fields = {
  图书管理员编号: "bookAdminId",
  用户名: "username",
  姓名: "bookAdminName",
  邮箱: "email",
};
const loading = ref(true);
onMounted(() => {
  getBookAdminList();
});

//导出excel
//导出excel
const exportToExcel = () => {
  //excel表格头部
  const headers = ["管理员ID", "账号", "账号", "邮箱"];
  // 转换表格数据为数组
  const ExcleData = tableData.value.map(item => [
    item.BookAdminID,
    item.Username,
    item.BorrowDate,
    item.BookAdminName,
    item.Email,
  ]);
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();
  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet([headers, ...ExcleData]);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  // 生成Excel文件
  XLSX.writeFile(workbook, "图书查询表格.xls");
};

const handleSizeChange = val => {
  queryInfo.pageSize = val;
  getBookAdminList();
};
const handleCurrentChange = val => {
  queryInfo.pageNum = val;
  getBookAdminList();
};
//让修改公告的对话框可见,并从数据库中回显数据
const showEditDialog = id => {
  editDialogVisible.value = true;
  editForm.bookAdminId = id;
  getOneAdmin(id)
    .then(res => {
      (editForm.userName = res.data.Username),
        // (editForm.password = res.data.Password),
        (editForm.email = res.data.Email),
        (editForm.bookAdminName = res.data.BookAdminName),
        ElMessage({
          message: "获取信息成功",
          type: "success",
        });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });
  // 让修改公告的对话框可见
};

const updateBookAdmin = () => {
  postOneAdmin(editForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "修改借阅证成功",
        type: "success",
      });
    })
    .then(res => getBookAdminList())
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("修改借阅证失败");
    });
  editDialogVisible.value = false;
};

//监听修改对话框的关闭，一旦对话框关闭，就重置表单，回显数据
const editDialogClosed = () => {
  // $refs.editFormRef.resetFields();
};
//删除公告
const removeUserById = id => {
  // 弹框，询问用户是否删除数据
  delOneAdmin(id)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "删除规则成功",
        type: "success",
      });
    })
    .then(res => getBookAdminList())
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("删除规则失败");
    });
};
//监听添加公告对话框的关闭，一旦对话框关闭，就重置表单
const addDialogClosed = () => {
  // $refs.addFormRef.resetFields();
};
//当用户点击发送新公告时，让添加对话框的visible改为true
const showAddDialog = () => {
  addDialogVisible.value = true;
};

// 获取图书管理员列表
const getBookAdminList = () => {
  loading.value = true;
  getAdminList(queryInfo)
    .then(res => {
      tableData = res.data.records;
      total.value = parseInt(res.data.total);
      console.log(tableData, "111");
      ElMessage({
        message: "获取信息成功",
        type: "success",
      });
    })
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("获取信息失败");
    });

  loading.value = false;
};
//增加管理员
const addBookAdmin = async () => {
  await addFormRef.value.validate();
  addAdmin(addForm)
    .then(res => {
      console.log(res.data, "111");
      ElMessage({
        message: "增加管理员成功",
        type: "success",
      });
    })
    .then(res => getBookAdminList())
    .catch(err => {
      console.log(err, "err");
      ElMessage.error("增加管理员失败");
    });

  addDialogVisible.value = false;
};

const downLoad = () => {
  getPdf(title); //参数是下载的pdf文件名
};

const fullScreen = () => {
  // Dom对象的一个属性: 可以用来判断当前是否为全屏模式(trueORfalse)
  let full = document.fullscreenElement;
  // 切换为全屏模式
  if (!full) {
    // 文档根节点的方法requestFullscreen实现全屏模式
    document.documentElement.requestFullscreen();
  } else {
    // 退出全屏模式
    document.exitFullscreen();
  }
};
</script>

<style></style>
